package ydd.yykj.dl.com.rx3;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import rx.Observable;
import rx.Scheduler;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    ImageView iv;
    Button btn;
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv = (ImageView) findViewById(R.id.iv);
        btn = (Button) findViewById(R.id.btn);
        tv = (TextView) findViewById(R.id.tv);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                start();
            }
        });
    }
    static StringBuffer sb = new StringBuffer();
    private void start(){

        Observable.create(new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> subscriber) {
                sb.append(" Observable.create(): 线程: "+Thread.currentThread().getName()+"\n\n");
                subscriber.onNext(R.mipmap.coolpro_mt_show_pic1);
                subscriber.onCompleted();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .map(new Func1<Integer, Bitmap>() {
            @Override
            public Bitmap call(Integer drawable) {
                sb.append("map():  Integer -->Bitmap 的线程: "+Thread.currentThread().getName()+"\n\n");
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(),drawable);
                return bitmap;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Bitmap>() {
            @Override
            public void call(Bitmap bitmap) {
                sb.append("call(): 线程: "+Thread.currentThread().getName()+"\n");
                tv.setText(sb);
                iv.setImageBitmap(bitmap);
            }
        });
    }
}
